package com.supermap.component.impl;

import java.util.HashSet;
import java.util.Set;

import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

import com.supermap.component.MatcherComponent;

public class MatcherComponentImpl implements MatcherComponent {

    public Set<String> getMatcherStr(String srcStr, String regex) throws MalformedPatternException {
        Set<String> result = new HashSet<String>();
        Pattern p = new Perl5Compiler().compile(regex);
        Perl5Matcher matcher = new Perl5Matcher();
        PatternMatcherInput matcherInput = new PatternMatcherInput(srcStr);
        while (matcher.contains(matcherInput, p)) {
            String matchStr = matcher.getMatch().toString();
            result.add(matchStr);
        }
        return result;
    }

    public String deleteMatchStr(String srcStr, String regex) throws MalformedPatternException {
        Pattern p = new Perl5Compiler().compile(regex);
        PatternMatcherInput matcherInput = new PatternMatcherInput(srcStr);
        Perl5Matcher matcher = new Perl5Matcher();
        while (matcher.contains(matcherInput, p)) {
            String matchStr = matcher.getMatch().toString();
            srcStr = srcStr.replace(matchStr, "");
        }
        return srcStr;
    }

    public boolean containsRegex(String srcStr, String regex) throws MalformedPatternException {
        PatternMatcherInput matcherInput = new PatternMatcherInput(srcStr);
        Pattern pattern = new Perl5Compiler().compile(regex);
        return new Perl5Matcher().contains(matcherInput, pattern);
    }

}
